package io.web.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.web.api.service.UserInterfaceInfoService;
import io.web.vo.HelloVo;
import io.web.api.ApiClient;
import io.web.api.ApiClientVo;
import io.web.api.annotation.AuthCheck;
import io.web.api.annotation.RPC;
import io.web.utils.BaseResponse;
import io.web.api.common.DeleteRequest;
import io.web.utils.ErrorCode;
import io.web.api.common.ResultUtils;
import io.web.api.constant.UserConstant;
import io.web.utils.BusinessException;
import io.web.api.exception.ThrowUtils;
import io.web.api.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import io.web.api.model.dto.interfaceinfo.InterfaceInfoEditRequest;
import io.web.api.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import io.web.api.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import io.web.api.model.entity.InterfaceInfo;
import io.web.api.model.entity.User;
import io.web.api.model.enums.InterfaceInfoStatusEnum;
import io.web.api.model.vo.InterfaceInfoVO;
import io.web.api.service.InterfaceInfoService;
import io.web.api.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * InterfaceInfo api
 *
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private UserService userService;

    @Autowired
    private ApiClient apiClient;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody @Validated InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newPostId = interfaceInfo.getId();
        return ResultUtils.success(newPostId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldPost = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPost.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceInfoEditRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody @Validated InterfaceInfoEditRequest interfaceInfoEditRequest) {
        if (interfaceInfoEditRequest == null || interfaceInfoEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoEditRequest, interfaceInfo);
        long id = interfaceInfoEditRequest.getId();
        // 判断是否存在
        InterfaceInfo oldPost = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVO(interfaceInfo, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<InterfaceInfoVO>> listInterfaceInfoVOByPage(
            @RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest,
            HttpServletRequest request) {
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> postPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(interfaceInfoQueryRequest));
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<InterfaceInfoVO>> listMyInterfaceInfoVOByPage(
            @RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest,
            HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        interfaceInfoQueryRequest.setUserId(loginUser.getId());
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<InterfaceInfo> postPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(interfaceInfoQueryRequest));
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVOPage(postPage, request));
    }

    // endregion


    // region 接口发布、下线

    /**
     * 发布（仅管理员）
     *
     * @param id
     * @return
     */
    @GetMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> online(@RequestParam("id") Long id, HttpServletRequest request) {
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(interfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);

        User loginUser = userService.getLoginUser(request);

        HelloVo helloVo = new HelloVo();
        helloVo.setMessage("hello api client");
        ApiClientVo clientVo = ApiClientVo.builder()
                .url(interfaceInfo.getUrl())
                .method(interfaceInfo.getRequestMethod())
                .body(interfaceInfo.getRequestParams())
                .accessKey(loginUser.getAccessKey())
                .secretKey(loginUser.getSercetKey())
                .build();
        Object res = apiClient.request(clientVo);
        if (res == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        InterfaceInfo updateInfo = new InterfaceInfo();
        updateInfo.setId(id);
        updateInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(updateInfo);
        return ResultUtils.success(result);
    }

    /**
     * 下线（仅管理员）
     *
     * @param id
     * @return
     */
    @GetMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offline(@RequestParam("id") Long id) {
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(interfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);

        InterfaceInfo updateInfo = new InterfaceInfo();
        updateInfo.setId(id);
        updateInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(updateInfo);
        return ResultUtils.success(result);
    }

    /**
     * 接口调用
     *
     * @param interfaceInfoInvokeRequest
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invoke(@RequestBody @Validated InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        long id = interfaceInfoInvokeRequest.getId();
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(interfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);

        Integer status = interfaceInfo.getStatus();
        ThrowUtils.throwIf(Objects.equals(status, InterfaceInfoStatusEnum.OFFLINE.getValue()), new BusinessException(-1, "接口已下线"));

        String headers = interfaceInfo.getRequestHeader();
//        Map<String, String> headerMap = JSONUtil.toBean(headers, Map.class);
        User loginUser = userService.getLoginUser(request);

        // 判断是否有调用次数
        boolean hasTimes = userInterfaceInfoService.checkTimes(interfaceInfo.getId(), loginUser.getId());
        ThrowUtils.throwIf(hasTimes, new BusinessException(-1, "调用次数已用完"));

        ApiClientVo clientVo = ApiClientVo.builder()
                .url(interfaceInfo.getUrl())
                .method(interfaceInfo.getRequestMethod())
//                .headers(headerMap)
                .body(interfaceInfoInvokeRequest.getRequestParams())
                .accessKey(loginUser.getAccessKey())
                .secretKey(loginUser.getSercetKey())
                .build();
        Object result = apiClient.request(clientVo);
        return ResultUtils.success(result);
    }
    // endregion

    /**
     * 判断接口是否存在
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @PostMapping("/findInterfaceInfo")
    @RPC
    public InterfaceInfo findInterfaceInfo(@RequestBody @Validated InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        String url = interfaceInfoQueryRequest.getUrl();
        String method = interfaceInfoQueryRequest.getRequestMethod();
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("url", url);
        queryWrapper.eq("requestMethod", method);
        return interfaceInfoService.getOne(queryWrapper);
    }

}
